var wfId = parent.$("#viewWorkFlow").attr("wfId") || ""
    ,maxX = 0
    ,maxY = 0
    ,aList = null
    ,LINE_RENDER_COLOR = "skyblue";
var viewStyle = {
    Connector: ["Flowchart", {
        stub: [0, 18],
        gap: 0,
        cornerRadius: 5,
        alwaysRespectStubs: false
    }],
    Endpoint: ["Dot", {}],
    ConnectionsDetachable: false,
    MaxConnections: -1,
    ConnectionOverlays: [
        ["Arrow", {
            location: 1,
            width: 10,
            length: 10,
            paintStyle: {
                fill: flowchart_color_default
            }
        }]
    ],
    EndpointStyle: {
        radius: 0.1,
        fill: flowchart_color_default
    },
    PaintStyle: {
        outlineStroke: flowchart_color_default,
        strokeWidth: 0
    }
}
var renderLine = {
    Connector: ["Flowchart", {
        stub: [0, 18],
        gap: 0,
        cornerRadius: 5,
        alwaysRespectStubs: false
    }],
    Endpoint: ["Dot", {}],
    ConnectionsDetachable: false,
    MaxConnections: -1,
    ConnectionOverlays: [
        ["Arrow", {
            location: 1,
            width: 15,
            length: 13,
            paintStyle: {
                fill: LINE_RENDER_COLOR
            }
        }]
    ],
    EndpointStyle: {
        radius: 0.1,
        fill: LINE_RENDER_COLOR
    },
    PaintStyle: {
        outlineStroke: LINE_RENDER_COLOR,
        strokeWidth: 2
    }
}
var viewJsPlum = jsPlumb.getInstance(viewStyle);

$(document).ready(function () {

    jsPlumb.ready(function () {
        getNodes();

    });

    $(window).resize(function() {
        window.location.reload();
    });

})

function getNodes() {
    var url = '/wf/activity/list';
    ActHttpRequest(url, {'wfId': wfId}, function (data) {
        if (data.OK != "OK") {
            layer.alert(data.message);
            return;
        }
        aList = data.List;
        reZoom();
    }, null, null, null, '读取中。。。', false);
}
function reZoom() {
    if (aList == null)  return;

    $('#flowchart').html("");

    for (var i = 0; i < aList.length; i++) {
        var activity = aList[i];

        if (parseFloat(activity.positionY) > maxY) maxY = activity.positionY;
        if (parseFloat(activity.positionX) > maxX) maxX = activity.positionX;
    }


    var f1,f2;
    f1 = window.innerWidth / (parseFloat(maxX) + 120);
    f2 = window.innerHeight / (parseFloat(maxY) + 120);
    if (f1 > f2) f1 = f2;
    if (f1 > 1) f1 = 1;
    if (f1 < 0.6) f1 = 0.6;

    for (var i = 0; i < aList.length; i++) {
        var activity = aList[i];
        activity.positionY *= f1;
        activity.positionX *= f1;
        var node = getSigleNodeHtml(activity);
        $('#flowchart').append(node);
    }
    $(".activity").css("font-size", 0.9*f1 + "em");
    $(".activity").css("width", 120*f1 + "px");
    $(".activity").css("height", 60*f1 + "px");
    getLines();

}
/*
* @author: wj
* @description: 获取连线
* @date: 2019/3/15 16:28
* @param
* @return
*/
function getLines() {
    var url = '/wf/activity/line/list';
    ActHttpRequest(url,{'wfId':wfId},function(data){
        if(typeof data.OK == 'undefined'){
            layer.alert('程序发生错误，请联系管理员处理！');
            return;
        }
        if(data.OK != "OK"){
            layer.alert(data.message);
            return;
        }
        var conns = data.List;
        var sourceId,sourcePoint,targetId,targetPoint,conditions,connLabel;

        for(var i=0;i<conns.length;i++){
            sourceId = conns[i].sourceId;
            sourcePoint = conns[i].sourcePoint;
            targetId = conns[i].targetId;
            targetPoint = conns[i].targetPoint;
            conditions = conns[i].conditions;

            if (conditions) connLabel = conObj2html(JSON.parse(conditions))

            viewJsPlum.connect({
                source:sourceId.toString(),
                target:targetId.toString(),
                anchors:[sourcePoint, targetPoint],
                overlays:[
                    [ "Label", {
                        label:connLabel,
                        location:0.36,
                        id:"conLabel",
                        labelStyle:{
                            color:"white",
                            fill:"gray"
                        }
                    }
                    ]
                ]
            });

        }
        //renderFunc();
    },null,null,null,'读取中。。。',false);
}
function getSigleNodeHtml(node) {
    var activityCode = node.activityCode;
    var id = node.wfaId;
    var className = 'activity';
    var nodeName = node.activityName;
    var nodeType = node.activityType;
    var executeUser = "【执行人】"
    if (nodeType == 'start' || nodeType == 'end') {
        className += ' ' + nodeType;
    }
    if (activityCode == "end" || activityCode == "start") {
        executeUser = ""
    } else if (activityCode == "001") {
        executeUser += "发起人"
    } else {
        strTtemp = getExecutor(id)
        if (!strTtemp) strTtemp = "（未配置）"
        executeUser += strTtemp
    }

    var html = '<div id="' + id + '" code="' + activityCode + '" class="' + className + '" activity_type="' + node['activityType'] + '" ' +
        'style="left:' + node['positionX'] + 'px;top:' + node['positionY'] + 'px;" title="' + executeUser + '">';
    html += '<span  class="activity_title"><div>' + nodeName + '</div><div>' + activityCode + '</div></span></br>';
    html += '</div>';

    return html;
}

/*
* 获取节点执行人*/
function getExecutor(iid) {
    var url = "/wf/activity/authority/list"
    var resUsers = ""

    $.ajax({
        async: false,
        type: 'post',
        url: url,
        data: { "activityId": iid},
        success: function (data) {
            data.List.forEach(function (iitem) {
                if (resUsers) resUsers += " "
                var strTitle = ""
                switch (iitem.flag) {
                    case 1:
                        strTitle = "(机构)"
                        break;
                    case 3:
                        strTitle = "(岗位)"
                        break;
                    case 4:
                        strTitle = "(角色)"
                        break;
                    case 5:
                        strTitle = "(用户)"
                        break;
                    case 6:
                        strTitle = "(计算)"
                        break;
                    case 7:
                        strTitle = "(指定环节办理人)"
                        break;
                }

                resUsers += strTitle + iitem.name
            })
        },
        complete: function (XMLHttpRequest, textStatus) {},
        error: function (a, b, c) {
            // 请求出错处理,依然初始化咨询节点信息
            if (b == 'timeout') {
                layer.alert("请求超时，请再次尝试！", {title: '错误信息：'});
            } else {
                layer.alert(url + "请求异常", {title: '错误信息：'});
            }
        }
    });

    if (resUsers) {
        resUsers = resUsers.replace(/,/g, " ")
    } else {
        resUsers = "（未配置）"
    }

    return resUsers
}

function conObj2html(conObj) {
    if (!conObj || conObj.length==0) return " "

    var strHtml = ""
    conObj.forEach(function (item) {
        if (strHtml) strHtml += "<br>"
        strHtml += item.fieldDisName
        strHtml += item.operatorName
        strHtml += item.conValueName
    })

    return strHtml
}